package com.ambition.mallchat.common.websocket;

import cn.hutool.core.util.StrUtil;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.ambition.mallchat.common.websocket.domain.enums.WSReqTypeEnum;
import com.ambition.mallchat.common.websocket.domain.enums.WSRespTypeEnum;
import com.ambition.mallchat.common.websocket.domain.vo.req.WSBaseReq;
import com.ambition.mallchat.common.websocket.service.WebsocketService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private WebsocketService websocketService;

    /**
     * 建立连接时进行保存通道事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        websocketService = SpringUtil.getBean(WebsocketService.class);
        websocketService.connect(ctx.channel());
    }

    /**
     * 用户登录时保存通道和code
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        WSBaseReq wsBaseReq = JSONUtil.toBean(text, WSBaseReq.class);
        WSReqTypeEnum wsReqTypeEnum = WSReqTypeEnum.of(wsBaseReq.getType());
        switch (wsReqTypeEnum){
            case AUTHORIZE:
                break;
            case HEARTBEAT:
                break;
            case LOGIN:
                websocketService.handeleLoginReq(channelHandlerContext.channel());
        }


    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            System.out.printf("握手完成");
        } else if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                System.out.printf("读空闲");
                //todo 用户下线
                offline(ctx.channel());
            }
        }
    }

    /**
     * 用户统一下线处理，关闭通道，移除Map
     * @param channel
     */
    public void offline(Channel channel){
        channel.close();
        websocketService.remove(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        offline(ctx.channel());
    }
}
